package socketdemo.io;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author zoush
 * @createTime 2024/12/03  17:15
 */
public class ServerDemo {
    public static void main(String[] args) {
        final int DEFAULT_PORT = 8888;
        try (ServerSocket serverSocket = new ServerSocket(DEFAULT_PORT)) {
            System.out.println("ServerSocket Start,The Port is:" + DEFAULT_PORT);
            //不停的监听端口
            while (true){
                Socket socket = serverSocket.accept();
                System.out.println("Client[" + socket.getPort() + "]Online");
                //接受消息
                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                //发送消息
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

                String msg = null ;
                while ((msg = reader.readLine()) != null){
                    System.out.println("Client[" + socket.getPort() + "]Send:" + msg);
                    //写入服务端要发送的消息
                    writer.write("Server Receive:" + msg + "\n");
                    writer.flush();

                    //如果客户端的消息是quit代表他退出了，并跳出循环，不用再接收他的消息了。如果客户端再次连接就会重新上线
                    if (msg.equals("")){
                        System.out.println("Client[" + socket.getPort() + "]:Offline");
                        break;
                    }
                }
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
